<template>
  <view v-for="(item, index) in ballList" :key="index">
    <view class="Ball" :style="item.ballStyle">
      <view class="inner" :style="item.ballInnerStyle">
        <uv-image :src="item.img" width="60rpx" height="60rpx" mode="aspectFit" radius="30rpx">
          <template v-slot:error>
            <view style="font-size: 24rpx">加载失败</view>
          </template>
        </uv-image>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
/**
 * inDomStyle 盒子动画开始时的top距离和left距离
 * toDomStyle 盒子动画结束时的top距离和left距离
 */
type DomStyleType = {
  left: number
  top: number
}
interface Props {
  inDomStyle: DomStyleType
  toDomStyle: DomStyleType
  ballImg: string
}
const props = withDefaults(defineProps<Props>(), {
  inDomStyle: () => ({
    left: 0,
    top: 0,
  }),
  toDomStyle: () => ({
    left: 0,
    top: 0,
  }),
  // 图片
  ballImg: '',
})
watch(
  () => props.ballImg,
  () => {
    console.log('收到的值,', props.inDomStyle, props.toDomStyle)
    addBall()
  },
)
const emit = defineEmits(['animationEnd'])
// 小球个数
const ballList = ref([])
// 控制小球的显隐
const showBall = ref(false)
const addBall = () => {
  ballList.value.push({
    ballStyle: {
      left: `${props.inDomStyle.left}px`,
      top: `${props.inDomStyle.top}px`,
    },
    ballInnerStyle: {
      left: '0px',
    },
    img: props.ballImg,
    // InnerStyleTop: `${props.toDomStyle.left - props.inDomStyle.left}`
  })
  addCart(ballList.value.length - 1)
}
// 向上偏移量
const deviationTop = 0
const addCart = (index) => {
  //   利用异步将其dom动画开始
  toInDom(index).then((res) => {
    setTimeout(() => {
      // showBall.value = false
      emit('animationEnd')
    }, 1000)
  })
}
const toInDom = (index) => {
  console.log(props.toDomStyle.left, props.inDomStyle.left, '12344')
  return new Promise((resolve) => {
    setTimeout(() => {
      ballList.value[index].ballInnerStyle.left = `${
        props.toDomStyle.left - props.inDomStyle.left
      }px`
      ballList.value[index].ballStyle.top = `${props.toDomStyle.top}px`
      resolve(true)
    }, 10)
  })
}
</script>

<style lang="scss" scoped>
.Ball {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 2;
  transition: all 1s cubic-bezier(0.49, -0.29, 0.75, 0.41);
  .inner {
    position: absolute;
    width: 60rpx;
    height: 60rpx;
    transition: all 1s linear;
  }
}
</style>
